﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerialPortTest
{
    internal class Program
    {
        //修改这里的下标，如果是多个数字，逗号分割，如果单个数字不要逗号
        static string WeighNumbers = "6,5";
        static int[] weighIndexes;
        static int[] WeighIndexes
        {
            get
            {
                if (weighIndexes == null)
                {
                    weighIndexes = WeighNumbers.Split(new char[] { ',' }).Select(x => Convert.ToInt32(x) - 1).ToArray();
                }
                return weighIndexes;
            }
        }
        //修改串口名称和波特率
        static SerialPort sp = new SerialPort("COM2", 115200);

        static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            int bytes = sp.BytesToRead;
            byte[] buffer = new byte[bytes];
            sp.Read(buffer, 0, bytes);
            Console.WriteLine($"收到长度{bytes}串口数据{BitConverter.ToString(buffer)}");
            try
            {
                byte[] b = WeighIndexes.Select(x => buffer[x]).ToArray();//修改字节数位，0开始
                int weight = BitConverter.ToInt16(b, 0);
                Console.WriteLine($"转换{BitConverter.ToString(b)}为十进制={weight}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
        static void Main(string[] args)
        {
            sp.DataReceived += SerialPort_DataReceived;

            try
            {
                sp.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("现在请测试称重，并检查数据是否正确，按任意键结束程序。。。");
            Console.ReadKey();
            try
            {
                sp.Close();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }
    }
}
